import { CanActivate, ExecutionContext, HttpException, HttpStatus, Injectable} from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import { DataSource } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private reflector: Reflector, @InjectDataSource() private datasource: DataSource) {}
    async canActivate(
        context: ExecutionContext
    ): Promise<boolean> {
        
        const req = context.switchToHttp().getRequest<Request>();
        if (!Reflect.has(req.session, 'actions')) {
            req.session['actions'] = [];
        }
        if (req.session['actions'].includes(req.url)) {
            try {
                await this.datasource.manager.query('set @log_url = ?', [req.url]);       
                await this.datasource.manager.query('set @log_oper = ?', [req.session['user']['name']]);
            } catch (err) {
                console.log(err);
                throw err;
            }
            
            return true;
        } else {
            //return false;
            throw new HttpException('没有权限', HttpStatus.BAD_REQUEST);
        }
    }
}
